package com.fauks.ssm.spring;

import com.fauks.ssm.spring.jdbc.JdbcCacheBean;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.ArrayList;
import java.util.List;

public class _03TestJdbc {

    private ApplicationContext ac;

    @Before
    public void createBeanFactory() {
        //1.创建Ioc容器对象
        ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-jdbc.xml");
    }


    //测试更新操作
    @Test
    public void testUpdate() {
        JdbcTemplate jdbcTemplate = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        String insertSQL = "INSERT INTO t_cache ( `name`, `desc`) VALUES (?,?)";
        int update = jdbcTemplate.update(insertSQL, "jdbctemplatename", "jdbctemplatedesc");
        System.out.println(update);
    }

    //测试批量插入
    @Test
    public void testBatck() {
        String insertSQL = "INSERT INTO t_cache ( `name`, `desc`) VALUES (?,?)";
        JdbcTemplate jdbcTemplate = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        List<Object[]> params = new ArrayList<>();
        params.add(new Object[]{"test1nam", "test1desc"});
        params.add(new Object[]{"test2nam", "test2desc"});
        params.add(new Object[]{"test3nam", "test3desc"});
        int[] ints = jdbcTemplate.batchUpdate(insertSQL, params);
        System.out.println(ints);
    }

    //测试查询单个bean
    @Test
    public void testQueryBean() {
        JdbcTemplate jdbcTemplate = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "select * from t_cache where id = ?";
        RowMapper<JdbcCacheBean> rowmapper = new BeanPropertyRowMapper<>(JdbcCacheBean.class);
        JdbcCacheBean bean = jdbcTemplate.queryForObject(sql, rowmapper, 2);
        System.out.println(bean);
    }

}
